package com.vy.stl.controller;

import com.vy.stl.constants.Constants;
import com.vy.stl.entity.Coach;
import com.vy.stl.service.CoachService;
import com.vy.stl.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.PropertyResolverUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @create: 2025/08/27 16:57
 * @description:
 */
@RestController //标识该类是一个控制器，自动将控制器方法的返回值转换为JSON格式
@RequestMapping("/coach") //定义该控制器处理的请求路径前缀
@Slf4j //简化日志对象的创建
public class CoachController {
    // Spring 的自动注入注解，用于将CoachService类型的Bean（服务层对象）自动注入到当前控制器中
    @Autowired
    private CoachService coachService;
    @Autowired
    private PropertyResolverUtils propertyResolverUtils;

    @GetMapping
    public Result getAll(Integer page, Integer limit, Coach coach) {
        if (ObjectUtils.isEmpty(page) && ObjectUtils.isEmpty(limit)) {
            return Result.success(Constants.STATUS_200,coachService.search(coach));
        }
        return Result.success(Constants.STATUS_200,coachService.searchByPage(page,limit,coach));
    }

    @PostMapping
    public Result add(@RequestBody Coach coach) {
        Coach dbCoach = coachService.getCoachByPhone(coach.getPhone());
        if (!ObjectUtils.isEmpty(dbCoach)) {
            return Result.error(-1,"手机号已存在");
        }
        try{
            coachService.add(coach);
            return Result.success(Constants.STATUS_200);
        }catch (Exception e){
            log.info(e.getMessage());
            return Result.error(-1,e.getMessage());
        }
    }

    @PutMapping
    public Result modify(@RequestBody Coach coach) {
        try {
            coachService.edit(coach);
            return Result.success(Constants.STATUS_200);
        }catch (Exception e){
            return Result.error(-1,e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result remove(@PathVariable("id") Integer id) {
        try{
            //加一个判断
            int row = coachService.remove(id);
            if (row > 0) {
                return Result.success(Constants.STATUS_200);
            }
            return Result.success(Constants.REMOVE_COACH_ERROR,"删除失败");
        } catch (Exception e) {
            log.info(e.getMessage());
            return Result.error(Constants.REMOVE_COACH_ERROR,e.getMessage());
        }
    }
}
